'use strict'

let sha1 = require('sha1')
let Promise = require('bluebird')
let request = Promise.promisify(require('request'))
let Wechat = require('./wechat')
let util = require('./util')
let getRawBody = require('raw-body')

module.exports = function(opts){

    let wechat = new Wechat(opts)

    return function *(next){

        let that = this

        let token = opts.token
        let signature = this.query.signature
        let nonce = this.query.nonce
        let timestamp = this.query.timestamp
        let echostr = this.query.echostr
        let str = [token, timestamp, nonce].sort().join('')
        let sha = sha1(str)

        if(this.method === 'GET'){
            if(sha == signature){
                this.body = echostr + ''
            }else{
                this.body = 'wrong'
            }
        }else if(this.method === 'POST'){
            if(!sha == signature){
                this.body = 'wrong'
                return false
            }
            let data = yield getRawBody(this.req, {
                length: this.length,
                limit: '1mb',
                encoding: this.charset
            })
            let content = yield util.parseXMLAsync(data)
            let message = util.formatMessage(content.xml)

            if(message.MsgType === 'event'){
                if(message.Event === 'subscribe'){
                    console.log(message)
                    let now = new Date().getTime()
                    that.status = 200
                    that.type = 'application/xml'
                    that.body = `<xml> <ToUserName>< ![CDATA[${message.FromUserName}] ]></ToUserName> <FromUserName>< ![CDATA[${message.ToUserName}] ]></FromUserName> <CreateTime>${now}</CreateTime> <MsgType>< ![CDATA[text] ]></MsgType> <Content>< ![CDATA[我爱你] ]></Content> </xml>`
                    return
                }
            }
        }
    }
}